﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dominio;
using Excepciones;
using System.Data.Objects.SqlClient;

namespace Servicios
{
    public class IndexServiceDataBaseImpl : IIndexService
    {

        private IFileSystemElementService fileSystemElementService = FabricaDeServicios.ObtenerInstancia().ObtenerFileSystemElementService();   

        private static IndexServiceDataBaseImpl instancia = new IndexServiceDataBaseImpl();

        private IndexServiceDataBaseImpl() : base() { }

        public static IndexServiceDataBaseImpl ObtenerInstancia()
        {
            return instancia;
        }

        public void AgregarIndice(FileSystemElement fse)
        {
            fileSystemElementService.Registrar(fse);
        }

        public void ModificarIndice(FileSystemElement fse)
        {
            fileSystemElementService.Modificar(fse);
        }

        public void BorrarIndice(FileSystemElement fse)
        {
            fileSystemElementService.Borrar(fse);
        }

        public IList<FileSystemElement> Buscar(string keyword)
        {
            //ver de usar indices 

            using (DominioContainer ctx = new DominioContainer())
            {
                if(ctx.FileSystemElements.Count(f => f != null) == 0){
                    return new List<FileSystemElement>();
                }
                List<FileSystemElement> fileSystemElements = new List<FileSystemElement>();
                try
                {
                    var query = from fse in ctx.FileSystemElements
                                where fse.Nombre.Contains(keyword) ||
                                fse.Ruta.Contains(keyword) ||
                                SqlFunctions.DateName("day",fse.Fecha).Contains(keyword) ||
                                SqlFunctions.DateName("month", fse.Fecha).Contains(keyword) ||
                                SqlFunctions.DateName("year", fse.Fecha).Contains(keyword)
                                select fse;

                    foreach (var fse in query)
                    {
                        fileSystemElements.Add(fse);
                    }

                    return fileSystemElements;
                }
                catch (Exception ex)
                {
                    throw new DataBaseException();
                }


            }
        }
    }
}
